<?php

namespace app\astrteam\controller;

use app\astrteam\model\Zlcr3ConsultTeam;
use app\common\lib\Aes;
use app\common\lib\AliOss;
use app\common\lib\exception\ApiException;
use think\Controller;
use think\Env;

class AstrTeamAuth extends Controller
{
    /**
     * headers信息
     * @var array
     */
    public $headers = [];

    public $uri = '';

    public $isLogin = false;
    /**
     * 登录用户的基本信息
     * @var array
     */
    public $teamInfo = null;

    /**
     * 初始化的方法
     * @throws ApiException
     */
    protected function _initialize()
    {
        $this->headers = $this->request->header();
        if (empty($this->uri))
        {
            $model = $this->request->module();
            $controller = $this->request->controller();
            $startNum = strpos($controller, '.');
            if ($startNum !== false)
            {
                $controller = substr($controller, $startNum + 1);
            }
            $action = $this->request->action(); // 全小写

            $this->uri = strtolower($model . '.' . $controller . '.' . $action);
        }

        // 获取用户登录信息
        $this->getLoginUserInfo();

        if (!$this->isLogin && $this->isMastLogin())
        {   // 未登录 判断接口是否需要登录  返回真则代表需要登录
            throw new ApiException('前往登录', 200, 405);
        }
    }

    /**
     * 判定是否登录
     * @throws ApiException
     */
    public function getLoginUserInfo()
    {
        if (!isset($this->headers['access-token']) || $this->headers['access-token'] == '') return;

        // access-token AES解密
        $accessUserToken = (new Aes())->decryptWithOpenssl($this->headers['access-token']);

        if (empty($accessUserToken)) return;

        if (!preg_match('/||/', $accessUserToken))
        {
            throw new ApiException('您的账户登录过期，请重新登录。', 200, config('code.denied'));
        }

        [$token, $id] = explode('||', $accessUserToken);

        $id = (int)($id);

        $userTeaminfo = (new Zlcr3ConsultTeam())->getInfoById($id);

        if (empty($userTeaminfo) || $userTeaminfo['token'] !== $token)
        {
            throw new ApiException('当前账号登录过期，请您重新登录。', 200, config('code.denied'));
        }
        // 判定时间是否过期
        if (time() > $userTeaminfo['token_expire'])
        {
            throw new ApiException('您的账户登录过期，请重新登录。', 200, config('code.denied'));
        }
        $this->teamInfo = $userTeaminfo;
        /**
         * 定义全局常量 UID 方便日志打印带上用户ID信息
         */
        if (!defined('USERINFO_UID'))
        {
            define('USERINFO_UID', $userTeaminfo['id']);
        }
        // 记录登录状态
        $this->isLogin = true;
    }

    /**
     * 接口是否必须登录
     * @return bool
     */
    public function isMastLogin()
    {
        $neednotLoginData = [ // 免绑登录接口

        ];
        if (in_array($this->uri, $neednotLoginData, true))
        {
            return false;
        }

        return true;
    }

    /**
     * 获取oss私有图片地址，注意：$path 是以 “/” 开头的
     * @param string $path
     * @return mixed|string
     */
    public function getOssPrivateUrl($path = '')
    {
        if ($path)
        {
            //获取私有图片地址
            $aliOss = AliOss::getInstance();
            $private_url = $aliOss->getAuth(substr($path, 1));
            return str_replace("http://zhunle.oss-cn-beijing.aliyuncs.com/", Env::get('host.photo'), $private_url);

        }
        return $path;
    }
}